/**
 * 样式函数
 * @param {number} time
 * @returns
 */
function timeout(time: number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
}

class SuperTask {
  taskList: any[];
  runTasks: any[];
  runCount: number;
  runMaxCount: number;

  constructor() {
    this.taskList = [];
    this.runCount = 0;
    this.runMaxCount = 2;
  }

  run() {
    while (this.runCount < this.runMaxCount && this.taskList.length) {
      const item = this.taskList.shift(); // 删除最前面一个任务
      item.fn().then((res) => {
        this.runCount--;
        item.resolve();
        this.run();
      });
    }
  }

  add(fn: () => void) {
    return new Promise((resolve, reject) => {
      // setTimeout(() => {
      //   resolve(true);
      // }, time);
      this.taskList.push({
        fn,
        resolve,
        reject,
      });
      this.run();
      // const item = this.taskList[0];
      // if (this.runTasks.length < this.max) {
      //   this.runIndex++;
      //   this.runTasks.push(fn);
      // }
    });
  }
}

const superTask = new SuperTask();

function addTask(time: number, name: any) {
  superTask
    .add(() => timeout(time))
    .then(() => {
      console.log("任务" + name + "完成");
    });
}

addTask(10000, 1);
addTask(5000, 2);
addTask(3000, 3);
addTask(4000, 4);

export {};
